import React, { createContext, useContext, useReducer } from 'react';

interface Account {
  id: string;
  platform: string;
  username: string;
  status: 'online' | 'offline' | 'error';
  lastActive?: Date;
}

interface CookieData {
  name: string;
  value: string;
  domain: string;
  path: string;
  expires?: number;
  httpOnly: boolean;
  secure: boolean;
}

interface TabSession {
  tabId?: string;
  accountId?: string;
  cookies: Map<string, CookieData>;
  localStorage: Map<string, any>;
  sessionStorage: Map<string, any>;
  userAgent?: string;
  createdAt: Date;
  lastActive: Date;
}

interface Tab {
  id: string;
  title: string;
  url: string;
  accountId?: string;
  webviewId?: string;
  isActive: boolean;
  isLoading?: boolean;
  sessionData?: TabSession;
  platform?: string;
  favicon?: string;
}

export type { Tab, TabSession, CookieData, Account };

interface AppState {
  accounts: Account[];
  tabs: Tab[];
  activeTabId: string | null;
  platforms: string[];
}

type AppAction =
  | { type: 'ADD_TAB'; payload: Tab }
  | { type: 'CLOSE_TAB'; payload: string }
  | { type: 'SWITCH_TAB'; payload: string }
  | { type: 'UPDATE_TAB_URL'; payload: { id: string; url: string } }
  | { type: 'ADD_ACCOUNT'; payload: Account }
  | { type: 'UPDATE_ACCOUNT_STATUS'; payload: { id: string; status: Account['status'] } }
  | { type: 'UPDATE_TAB_SESSION'; payload: { tabId: string; session: Partial<TabSession> } }
  | { type: 'SET_TAB_COOKIE'; payload: { tabId: string; cookie: CookieData } }
  | { type: 'REMOVE_TAB_COOKIE'; payload: { tabId: string; cookieName: string } }
  | { type: 'EXPORT_TAB_COOKIES'; payload: { tabId: string } };

const initialState: AppState = {
  accounts: [],
  tabs: [],
  activeTabId: null,
  platforms: ['抖音', '快手', '小红书', '微博', 'B站']
};

function appReducer(state: AppState, action: AppAction): AppState {
  switch (action.type) {
    case 'ADD_TAB':
      return {
        ...state,
        tabs: [...state.tabs, { ...action.payload, isActive: true }],
        activeTabId: action.payload.id
      };
    case 'CLOSE_TAB':
      const filteredTabs = state.tabs.filter(tab => tab.id !== action.payload);
      let newActiveTabId = state.activeTabId;
      if (state.activeTabId === action.payload && filteredTabs.length > 0) {
        newActiveTabId = filteredTabs[0].id;
      } else if (filteredTabs.length === 0) {
        newActiveTabId = null;
      }
      return {
        ...state,
        tabs: filteredTabs,
        activeTabId: newActiveTabId
      };
    case 'SWITCH_TAB':
      return {
        ...state,
        tabs: state.tabs.map(tab => ({
          ...tab,
          isActive: tab.id === action.payload
        })),
        activeTabId: action.payload
      };
    case 'UPDATE_TAB_URL':
      return {
        ...state,
        tabs: state.tabs.map(tab =>
          tab.id === action.payload.id ? { ...tab, url: action.payload.url } : tab
        )
      };
    case 'ADD_ACCOUNT':
      return {
        ...state,
        accounts: [...state.accounts, action.payload]
      };
    case 'UPDATE_ACCOUNT_STATUS':
      return {
        ...state,
        accounts: state.accounts.map(account =>
          account.id === action.payload.id
            ? { ...account, status: action.payload.status }
            : account
        )
      };
    case 'UPDATE_TAB_SESSION':
      return {
        ...state,
        tabs: state.tabs.map(tab =>
          tab.id === action.payload.tabId
            ? { 
                ...tab, 
                sessionData: { 
                  ...tab.sessionData, 
                  ...action.payload.session,
                  lastActive: new Date()
                } 
              }
            : tab
        )
      };
    case 'SET_TAB_COOKIE':
      return {
        ...state,
        tabs: state.tabs.map(tab => {
          if (tab.id === action.payload.tabId && tab.sessionData) {
            const newCookies = new Map(tab.sessionData.cookies);
            newCookies.set(action.payload.cookie.name, action.payload.cookie);
            return {
              ...tab,
              sessionData: {
                ...tab.sessionData,
                cookies: newCookies,
                lastActive: new Date()
              }
            };
          }
          return tab;
        })
      };
    case 'REMOVE_TAB_COOKIE':
      return {
        ...state,
        tabs: state.tabs.map(tab => {
          if (tab.id === action.payload.tabId && tab.sessionData) {
            const newCookies = new Map(tab.sessionData.cookies);
            newCookies.delete(action.payload.cookieName);
            return {
              ...tab,
              sessionData: {
                ...tab.sessionData,
                cookies: newCookies,
                lastActive: new Date()
              }
            };
          }
          return tab;
        })
      };
    default:
      return state;
  }
}

const AppContext = createContext<{
  state: AppState;
  dispatch: React.Dispatch<AppAction>;
} | null>(null);

export function AppProvider({ children }: { children: React.ReactNode }) {
  const [state, dispatch] = useReducer(appReducer, initialState);
  return (
    <AppContext.Provider value={{ state, dispatch }}>
      {children}
    </AppContext.Provider>
  );
}

export function useApp() {
  const context = useContext(AppContext);
  if (!context) {
    throw new Error('useApp must be used within an AppProvider');
  }
  return context;
}